package com.atguigu.srb.sms.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.srb.sms.service.SmsService;
import com.rabbitmq.client.Channel;
import javafx.scene.chart.ValueAxis;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Map;

@Configuration
public class SmsMqListener {
    @Autowired
    SmsService smsService;
    /*
            Map<String,String> result = new HashMap<>();
        result.put("mobile",userInfo.getMobile());
        result.put("content" , "充值成功");
        result.put("tplId" , "1001");
        //充值成功sms根据mq的消息发送短信
        rabbitTemplate.convertAndSend("srb.account.exchange","account.charge" ,
                JSON.toJSONString(result));
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                exchange = @Exchange(value = "srb.account.exchange" ,ignoreDeclarationExceptions = "true",
                                type = ExchangeTypes.TOPIC),
                    value = @Queue(value = "srb.account.charge.queue"),
                    key = "account.charge"
            )
    })
    public void chargeListener(Channel channel,String msg , Message message) throws IOException {

        try {
            //消费消息的业务： 发送短信
            Map<String,String> map = JSON.parseObject(msg, Map.class);
            String mobile = map.get("mobile");
            String content = map.get("content");
            smsService.sendNotifyMsg(mobile,content);
            //手动ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);
        } catch (Exception e) {
            e.printStackTrace();
            //消息消费失败
            if(message.getMessageProperties().isRedelivered()){
                //消息归队后重新消费失败了
                channel.basicReject(message.getMessageProperties().getDeliveryTag() , false);
            }else{
                //第一次消息消费失败，让消息返回队列
                channel.basicNack(message.getMessageProperties().getDeliveryTag() ,false, true);
            }
        }

    }

}
